package com.fujica.invoicing.service.impl;

import com.fujica.invoicing.entity.TInventory;
import com.fujica.invoicing.entity.TPurchase;
import com.fujica.invoicing.mapper.IInventoryMapper;
import com.fujica.invoicing.mapper.IPurchaseDetailMapper;
import com.fujica.invoicing.mapper.IPurchaseMapper;
import com.fujica.invoicing.request.purchase.PurchaseGoods;
import com.fujica.invoicing.request.purchase.PurchaseReq;
import com.fujica.invoicing.service.IPurchaseService;
import com.fujica.invoicing.utils.Result;
import com.fujica.invoicing.utils.ResultBody;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName PurchaseServiceImpl
 * @Description TODO
 * @Author cjm
 * @Date 2020/8/11 14:10
 * @Version 1.0
 **/
@Service
@Slf4j
public class PurchaseServiceImpl implements IPurchaseService {

    @Autowired
    private IPurchaseMapper iPurchaseMapper;
    @Autowired
    private IPurchaseDetailMapper iPurchaseDetailMapper;
    @Autowired
    private IInventoryMapper iInventoryMapper;

    /**
     * 进货   TODO
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)   // 异常自动回滚
    public Result purchase(PurchaseReq req) {

        // 获取当前时间
        Date now = new Date();

        // TODO 根据cookie 查找用户

        // TODO 先插入进货表 获取进货id 计算所有商品的总金额
        // 仓库id
        Integer depositoryId = req.getDepositoryId();
        // 供应商id
        Integer supplierId = req.getSupplierId();
        // 进货商品列表
        List<PurchaseGoods> purchaseGoods = req.getPurchaseGoods();
        // 计算商品总金额
        BigDecimal purAmount = purchaseGoods.stream().reduce(BigDecimal.ZERO, (x, y) -> {
            return x.add(y.getPurPrice().multiply(BigDecimal.valueOf(y.getPurNum())));
        }, BigDecimal::add);

        // 插入进货表的map
        TPurchase purchase = new TPurchase(depositoryId, 1, supplierId, purAmount, now);

        // 插入数据库 获取进货id
        iPurchaseMapper.insertPurchase(purchase);
        Integer purId = purchase.getId();
        log.debug("进货id:{}", purId);


        // 将获取商品id及价格、数量插入到进货明细
        purchaseGoods.forEach(item -> {
            Integer gId = item.getGoodsId();
            BigDecimal gPrice = item.getPurPrice();
            Integer purNum = item.getPurNum();

            // 逐条插入库存明细数据库
            Map insertPurDetailMap = Maps.newHashMap();
            insertPurDetailMap.put("purId", purId);
            insertPurDetailMap.put("gId", gId);
            insertPurDetailMap.put("purPrice", gPrice);
            insertPurDetailMap.put("purNum", purNum);
            iPurchaseDetailMapper.insertPurDetail(insertPurDetailMap);

            // 修改库存表 如果存在库存则修改 不存在则新增库存
            // 根据仓库id、商品id、商品价格进行查找
            TInventory preInventory = new TInventory();
            preInventory.setDId(depositoryId);
            preInventory.setGId(gId);
            preInventory.setGPrice(gPrice);
            TInventory inventory = iInventoryMapper.selectOne(preInventory);
            if (inventory != null) {
                // 存在该商品库存
                Map updateMap = Maps.newHashMap();
                updateMap.put("dId", depositoryId);
                updateMap.put("gId", gId);
                updateMap.put("gPrice", gPrice);
                // 增加库存量
                updateMap.put("inventory", inventory.getInventory() + purNum);
                // 修改时间
                updateMap.put("iUpdate", now);
                iInventoryMapper.updateInventory(updateMap);
            } else {
                // 不存在该商品库存
                inventory = new TInventory();
                inventory.setDId(depositoryId);
                inventory.setGId(gId);
                inventory.setGPrice(gPrice);
                inventory.setInventory(purNum);
                inventory.setICreate(now);
                inventory.setIUpdate(now);
                iInventoryMapper.insertSelective(inventory);
            }

        });
        return ResultBody.ok();
    }
}
